package cn.edu.sdyu.ie.crs.service.impl;

import cn.edu.sdyu.ie.crs.common.response.LabelValue;
import cn.edu.sdyu.ie.crs.domain.Assignment;
import cn.edu.sdyu.ie.crs.domain.Classroom;
import cn.edu.sdyu.ie.crs.repository.AssignmentRepository;
import cn.edu.sdyu.ie.crs.service.AssignmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class AssignmentServiceImpl implements AssignmentService {

    @Autowired
    private AssignmentRepository assignmentRepository;

    @Override
    public List<Assignment> findAll() {
        return assignmentRepository.findAll();
    }

    @Override
    public Page<Assignment> findByPage(Integer page, Integer pageSize) {
        Pageable pageable = PageRequest.of(page, pageSize, Sort.by(Sort.Direction.DESC,"id"));
        return assignmentRepository.findAll(pageable);
    }

    @Override
    public Assignment findAssignmentById(Integer id) {
        Optional<Assignment> optional = assignmentRepository.findById(id);
        if(optional.isPresent()) {
            return optional.get();
        } else {
            log.warn("指定分配信息[ID:{}]不存在", id);
            return null;
        }

        // return assignmentRepository.findById(id).orElse(null);
    }

    @Override
    public void saveAssignment(Assignment assignment) {
        if(assignment.getId() == null) {
            assignment.setCreateTime(new Date());
        }
        assignmentRepository.save(assignment);
    }

    @Override
    public void deleteAssignmentById(Integer id) {
        assignmentRepository.deleteById(id);
    }

    @Override
    public List<LabelValue> countGroupByExecutionDateBetween(LocalDate startDate, LocalDate endDate) {

        List<LabelValue> list = assignmentRepository.countGroupByExecutionDateBetween(startDate, endDate);
        return list;
    }

    @Override
    public List<Assignment> findAvailableAssignments(String user) {
        return assignmentRepository.findAssignmentsByUserAndState(user, 1);
    }
}